package Thread;

import java.util.concurrent.atomic.AtomicInteger;
//CAS方式实现(原子类)，比加锁更高效，不涉及阻塞等待
public class ThreadDemo30 {
    //不使用原生的int，也不加锁保证线程安全，而是替换成AtomicInteger
    //private static int count=0;
    private static AtomicInteger count=new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        Object locker=new Object();
        Thread t1=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                //count++;
                count.getAndIncrement();
            }
        });
        Thread t2=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                count.getAndIncrement();
            }
        });
        t1.start();
        t2.start();
        // 如果没有这俩 join, 肯定不⾏的. 线程还没⾃增完, 就开始打印了. 很可能打印出来的 count是初始未累加的值0，或者计算过程中的不准确的值
        t1.join();
        t2.join();
        // 预期结果应该是 10w
        System.out.println("count: " + count.get());

    }
}
